package cn.codergege.shiro.chapter6.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import cn.codergege.shiro.chapter6.dao.RoleDao;
import cn.codergege.shiro.chapter6.model.Role;

@Repository("roleDao")
public class RoleDaoImpl implements RoleDao {

	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public Role createRole(Role role) throws Exception {
        final String sql = "insert into sys_roles(role, description, available) values(?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" });
				ps.setString(1, role.getRole());
				ps.setString(2, role.getDescription());
				ps.setBoolean(3, role.getAvailable());
				return ps;
			}
		}, keyHolder);
        role.setId(keyHolder.getKey().longValue());
		return role;
	}

	@Override
	public void deleteRole(Long roleId) throws Exception {
        String sql = "delete from sys_users_roles where role_id=?";
        jdbcTemplate.update(sql, roleId);
        // sys_roles_permissions 中相关的 role 可以不用删
        
        sql = "delete from sys_roles where id=?";
        jdbcTemplate.update(sql, roleId);
	}

	@Override
	public void correlationPermissions(Long roleId, Long... permissionIds) throws Exception {
		if(permissionIds == null || permissionIds.length == 0) {
			return;
		}
        String sql = "insert into sys_roles_permissions(role_id, permission_id) values(?,?)";
        for(Long permissionId: permissionIds) {
        	if(exists(roleId, permissionId)) {
        		jdbcTemplate.update(sql, roleId, permissionId);
        	}
        }
	}

	@Override
	public void uncorrelationPermissions(Long roleId, Long... permissionIds) throws Exception {
		if(permissionIds == null || permissionIds.length == 0) {
			return;
		}
        String sql = "delete from sys_roles_permissions where role_id=? and permission_id=?";
        for(Long permissionId: permissionIds) {
        	if(exists(roleId, permissionId)) {
        		jdbcTemplate.update(sql, roleId, permissionId);
        	}
        }
	}

	private boolean exists(Long roleId, Long permissionId) {
        String sql = "select count(1) from sys_roles_permissions where role_id=? and permission_id=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, roleId, permissionId) != 0;
	}
}
